//
//  Speech.m
//  PeopleForTheFirstMall
//
//  Created by iOS on 2020/11/27.
//  Copyright © 2020 MS. All rights reserved.
//

#import "Speech.h"

@interface Speech ()
<
AVSpeechSynthesizerDelegate
>

@property (nonatomic, strong) AVSpeechSynthesizer   *avSpeech;
@property (nonatomic, strong) NSLock                *lock;

@end

@implementation Speech

ms_implementation(Speech)

/** 播报 */
- (void)speech:(NSString *)string
{
    if (string && string.length > 0)
    {
        [[self mainQueue] addOperation:[self customOperation:string]];
    }
}

- (NSOperationQueue *)mainQueue
{
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    queue.maxConcurrentOperationCount = 1;
    return queue;
}

- (NSOperation *)customOperation:(NSString *)content {
    
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        
        AVSpeechUtterance *utterance = nil;
        @autoreleasepool {
            utterance = [AVSpeechUtterance speechUtteranceWithString:content];
            utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
            utterance.pitchMultiplier = 0.1; // 声调
            utterance.volume = 1;// 音量
            utterance.rate = 0.5;// 语速
            utterance.pitchMultiplier = 1.1;
        }
        
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
                                               error:nil];
        [[AVAudioSession sharedInstance] setActive:YES
                                             error:nil];
        
        [self.avSpeech speakUtterance:utterance];
        
    }];
    return operation;
}


#pragma mark - AVSpeechSynthesizerDelegate

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didStartSpeechUtterance:(AVSpeechUtterance *)utterance
{
    [self.lock lock];
}

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance
{
    [self.lock unlock];
}


- (AVSpeechSynthesizer *)avSpeech
{
    if (!_avSpeech)
    {
        _avSpeech = [[AVSpeechSynthesizer alloc] init];
        _avSpeech.delegate = self;
    }
    
    return _avSpeech;
}

- (NSLock *)lock
{
    if (!_lock)
    {
        _lock = [[NSLock alloc] init];
    }
    
    return _lock;
}

@end
